package br.com.mundodaprata.store.model;

import java.io.Serializable;

import br.com.mundodaprata.store.data.Repository;
import br.com.mundodaprata.store.data.RepositoryFactoryJPA;

public abstract class AbstractEntity implements Serializable, Persistable{
	
	private static final long serialVersionUID = 1L;

	public abstract Long getCode();
	
	@Override
	@SuppressWarnings("unchecked")
	public void save() throws Exception {
		Repository<AbstractEntity> repository = 
				(Repository<AbstractEntity>) RepositoryFactoryJPA.create(getClass());
		
		if(getCode() == null){
			repository.insert(this);
		}
		else{
			repository.update(this);
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public void delete() throws Exception {
		Repository<AbstractEntity> repository = 
				(Repository<AbstractEntity>) RepositoryFactoryJPA.create(getClass());
		
		repository.remove(this);		
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((getCode() == null) ? 0 : getCode().hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof AbstractEntity)) {
			return false;
		}
		AbstractEntity other = (AbstractEntity) obj;
		if (getCode() == null) {
			if (other.getCode() != null) {
				return false;
			}
		} else if (!getCode().equals(other.getCode())) {
			return false;
		}
		return true;
	}

}